package com.unionftech.common.recaptcha.aliyun

import android.os.Handler
import android.os.Looper
import android.webkit.JavascriptInterface
import org.json.JSONObject

class AliyunCaptchaJsInterface(
    val webView: AliyunCaptchaWebView,
    var listener: AliyunCaptchaListener? = null
) {
    private val mMainHandler = Handler(Looper.getMainLooper())

    @JavascriptInterface
    fun getVerifyResult(jsonString: String) {
        val jsonObject = JSONObject(jsonString)
        val captchaVerifyParam = jsonObject.optString("data")
        val callbackName = jsonObject.optString("callback")
        // 用captchaVerifyParam请求后端接口拿到请求结果
        serviceVerifyAndReturnResult(captchaVerifyParam, callbackName)
    }

    @JavascriptInterface
    fun closeWebView() {
        mMainHandler.post {
            listener?.onClose()
        }
    }

    private fun serviceVerifyAndReturnResult(captchaVerifyParam: String, callbackName: String?) {
        mMainHandler.post {
            listener?.also {
                it.onValidate(captchaVerifyParam) { captchaResult ->
                    handleVerifyResult(captchaResult, callbackName)
                }
            } ?: handleVerifyResult(false, callbackName)
        }
    }

    private fun handleVerifyResult(captchaResult: Boolean, callbackName: String?) {
        val result = JSONObject()
        // 这里模拟一下返回结果
        result.put("captchaResult", captchaResult)
        result.put("bizResult", true)
        // result可以转换为一个JSON字符串，注意传给H5之后的数据格式转换
        val resultString = result.toString()
        // 处理完数据后，将结果回传给H5页面
        // 这里需要确保操作在主线程(UI线程)中执行
        evaluateJavascript(callbackName, resultString)
    }

    private fun evaluateJavascript(callbackName: String?, resultString: String) {
        // 使用evaluateJavascript发送回调到H5页面
        webView.evaluateJavascript(
            "javascript:"
                    + callbackName + "('" + escapeJavaScriptString(resultString) + "')",
            null
        )
        // 根据result在App测来执行业务自定义提示逻辑，H5中的onBizResultCallback可以置为空函数
    }

    // 对JavaScript字符串进行转义，避免JavaScript注入问题
    private fun escapeJavaScriptString(string: String): String? {
        // 这是一个简单的转义示例。对于更复杂的情况，可能需要更有效的转义方法
        return string.replace("'", "\\'")
            .replace("\n", "\\n")
            .replace("\r", "\\r")
            .replace("\"", "\\\"")
    }
}